//
//  AppDelegate.m
//  BaseProject
//
//  Created by 王洋 on 2020/3/19.
//  Copyright © 2020 王洋. All rights reserved.
//

#import "AppDelegate.h"
#import "TT_IMManager.h"

#import <AlipaySDK/AlipaySDK.h>

#import "TT_WebviewController.h"
#import "TSPushNotificationView.h"

#import "TT_TabbarViewController.h"


@import TXLiteAVSDK_Professional;

@interface AppDelegate ()<WXApiDelegate>

@property (nonatomic, assign) BOOL done;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [self initThirdSDK];
    [self initRoot];
    [self cleanWebCach];

    return YES;
}

- (void)cleanWebCach {
    NSArray * types =@[WKWebsiteDataTypeMemoryCache,WKWebsiteDataTypeDiskCache]; // 9.0之后才有的
    NSSet *websiteDataTypes = [NSSet setWithArray:types];
    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
        NSLog(@"清空了wkwebview的缓存");
    }];
}

- (void)initThirdSDK {
    
//    [[TT_IMManager sharedInstance] initWithAppKey:1400361025];
    
    /**
     *  向微信终端注册ID，这里的APPID一般建议写成宏,容易维护。@“测试demo”不需用管。这里的id是假的，需要改这里还有target里面的URL Type
     */
    [WXApi registerApp:WXAppId universalLink:@"https://card.hongmushichang.com/.well-known/apple-app-site-association/"];

    // 通过个推平台分配的appId、 appKey 、appSecret 启动SDK，注：该方法需要在主线程中调用
    [GeTuiSdk startSdkWithAppId:kGtAppId appKey:kGtAppKey appSecret:kGtAppSecret delegate:self];
    
    [self registerRemoteNotification];
    [[UIApplication sharedApplication] registerForRemoteNotifications];

    [self setbadge:0];
    
    [IQKeyboardManager sharedManager].enable = YES;
    
    NSString * const licenceURL = @"http://license.vod2.myqcloud.com/license/v1/13bdd55ebc1926cd3d526eec426ff8b0/TXLiveSDK.licence";
    NSString * const licenceKey = @"4bf5de131a015e7118d5415f134f2ea8";
    //TXLiveBase 位于 "TXLiveBase.h" 头文件中
    [TXLiveBase setLicenceURL:licenceURL key:licenceKey];
    NSLog(@"SDK Version = %@", [TXLiveBase getSDKVersionStr]);

    [[TT_IMManager sharedInstance] TTIM_InitSDK];
}

- (void)initRoot {

    TT_TabbarViewController *tabBarController = [TT_TabbarViewController shareTabbar];
    self.window.rootViewController = tabBarController;
}

#pragma mark push------GeTui SDK Method------push
/** 注册 APNs */
- (void)registerRemoteNotification {
    /*
     警告：Xcode8 需要手动开启"TARGETS -> Capabilities -> Push Notifications"
     */

    /*
     警告：该方法需要开发者自定义，以下代码根据 APP 支持的 iOS 系统不同，代码可以对应修改。
     以下为演示代码，注意根据实际需要修改，注意测试支持的 iOS 系统都能获取到 DeviceToken
     */
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 // Xcode 8编译会调用
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
            if (!error) {
                NSLog(@"request authorization succeeded!");
            }
        }];

        [[UIApplication sharedApplication] registerForRemoteNotifications];
#else // Xcode 7编译会调用
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
#endif
    } else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    } else {
        UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert |
                                                                       UIRemoteNotificationTypeSound |
                                                                       UIRemoteNotificationTypeBadge);
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
    }
}

#pragma mark push------SDK收到透传消息回调
- (void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId andOffLine:(BOOL)offLine fromGtAppId:(NSString *)appId {
    //收到个推消息
    NSString *payloadMsg = nil;
    if (payloadData) {
        payloadMsg = [[NSString alloc] initWithBytes:payloadData.bytes length:payloadData.length encoding:NSUTF8StringEncoding];
    }
    NSDictionary *dic = [Utilities getParams:payloadMsg];
    if ([dic isKindOfClass:[NSDictionary class]] && [dic.allKeys containsObject:@"content"]) {


        //app内显示弹窗
    }
    
    //收到推送，让AI追踪显示点
    if ([dic isKindOfClass:[NSDictionary class]] && [dic.allKeys containsObject:@"payload"]) {

        NSString *payload = [dic valueForKey:@"payload"];
        NSDictionary * payloadDic = [Utilities convert2DictionaryWithJSONString:payload].mutableCopy;
        TT_JumpModel * payloadModel = [TT_JumpModel mj_objectWithKeyValues:payloadDic];
        //AI追踪唯一的数据来源
        if (payloadModel.type == TT_JUMPTYPE_AITracking) {
            [[TTUserModel sharedObject].userModelDefault setValue:@"1" forKey:@"HY_newTrackingTag"];
            [[TTUserModel sharedObject].userModelDefault synchronize];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"HY_NewAttract" object:nil userInfo:nil];
        }
    }    
    
    NSString *msg = [NSString stringWithFormat:@"taskId=%@,messageId:%@,payloadMsg:%@%@",taskId,msgId, payloadMsg,offLine ? @"<离线消息>" : @""];
    NSLog(@"\n>>>[GexinSdk ReceivePayload]:%@\n\n", msg);
}

- (void)GeTuiSdkDidAliasAction:(NSString *)action result:(BOOL)isSuccess sequenceNum:(NSString *)aSn error:(NSError *)aError {
    if ([kGtResponseBindType isEqualToString:action]) {
        NSLog(@"绑定结果 ：%@ !, sn : %@", isSuccess ? @"成功" : @"失败", aSn);
        if (!isSuccess) {
            NSLog(@"失败原因: %@", aError);
        }
    } else if ([kGtResponseUnBindType isEqualToString:action]) {
        NSLog(@"绑定结果 ：%@ !, sn : %@", isSuccess ? @"成功" : @"失败", aSn);
        if (!isSuccess) {
            NSLog(@"失败原因: %@", aError);
        }
    }
}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    //外部激活
    if([[url absoluteString] rangeOfString:@"huayuancall://"].location == 0) {
        
        NSString *urlStr = [url absoluteString];
        urlStr = [Utilities stringByReplacingPercentEscapesUsingEncoding:urlStr];
        if ([urlStr hasPrefix:@"huayuancall://"]) {

            NSString *parameter = [urlStr stringByReplacingOccurrencesOfString:@"huayuancall://param?" withString:@""];
            
            if (![parameter hasPrefix:@"huayuancall://"]) {
                
                NSDictionary *dic = [Utilities getUrlParam:parameter];

                [[TT_JumpManager sharedManager] jumpWithWebParamDic:dic];

                NSLog(@"%@",dic);
                
            } else {
                
            }
        }
    }
    
    
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            NSString * isPaySuccess = @"0";
            NSString * msg = [resultDic objectForKey:@"memo"];;
            switch ([[resultDic objectForKey:@"resultStatus"] integerValue]) {
                case 6001: {
                    isPaySuccess = @"0";
                    msg = @"用户中途取消";
                } break;
                case 6002: {
                    isPaySuccess = @"0";
                    msg = @"网络连接出错";
                } break;
                case 6004: {
                    isPaySuccess = @"0";
                    msg = @"支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态";
                } break;
                case 4000: {
                    isPaySuccess = @"0";
                    msg = @"支付失败";
                } break;
                case 8000: {
                    isPaySuccess = @"0";
                    msg = @"正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态";
                } break;
                case 9000: {
                    isPaySuccess = @"1";
                    msg = @"支付成功";
                } break;
                default:
                    break;
            }
            
            NSMutableDictionary *payDic = @{}.mutableCopy;
            [payDic setValue:msg forKey:@"memo"];
            [payDic setValue:msg forKey:@"msg"];
            [payDic setValue:@"alipay" forKey:@"payType"];

            [payDic setValue:isPaySuccess forKey:@"resultStatus"];
            [payDic setValue:[resultDic objectForKey:@"resultStatus"] forKey:@"code"];

            [[NSNotificationCenter defaultCenter] postNotificationName:@"payResultNotification" object:nil userInfo:payDic];
        }];
    }
    
    if ([[url absoluteString] rangeOfString:@"wx00361f2e18fd26d2://pay"].location == 0){
        //这里判断是否发起的请求为微信支付，如果是的话，用WXApi的方法调起微信客户端的支付页面（://pay 之前的那串字符串就是你的APPID，）
        return [WXApi handleOpenURL:url delegate:self];
        
        //        return [WXApi handleOpenURL:url delegate:self];
    }else if([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回authCode
        
        return YES;
    }else if ([url.host containsString:@"platformId=wechat"]){//微信分享
        return [WXApi handleOpenURL:url delegate:self];
    }else if ([url.host containsString:@"resendContextReqByScheme"]){//微信登录
        return [WXApi handleOpenURL:url delegate:self];
    }else if ([url.host containsString:@"oauth"]){//微信登录
        return [WXApi handleOpenURL:url delegate:self];
    }
    
    
    
    return YES;
}

//微信SDK自带的方法，处理从微信客户端完成操作后返回程序之后的回调方法,显示支付结果的
-(void)onResp:(BaseResp*)resp
{
    //启动微信支付的response
    NSString *payResoult = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回的结果, 实际支付结果需要去微信服务器端查询
        NSString *isPaySuccess = @"0";
        NSString *msg = @"";
        id errorCode = @(resp.errCode);
        switch (resp.errCode) {
            case WXSuccess: {
                isPaySuccess = @"1";
                msg = @"支付成功";
            } break;
            case WXErrCodeUserCancel: {
                isPaySuccess = @"0";
                msg = @"用户取消了支付";
            } break;
            default: {
                isPaySuccess = @"0";
                msg = @"支付失败";
            } break;
        }
        
        NSMutableDictionary *payDic = @{}.mutableCopy;
        [payDic setValue:msg forKey:@"memo"];
        [payDic setValue:msg forKey:@"msg"];
        [payDic setValue:@"wechat" forKey:@"payType"];
        [payDic setValue:errorCode forKey:@"code"];
        [payDic setValue:isPaySuccess forKey:@"resultStatus"];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"payResultNotification" object:nil userInfo:payDic];
        
    }else  if([resp isKindOfClass:[SendMessageToWXResp class]]) {
          
        NSLog(@"resp.errCode-------%d",resp.errCode);
          switch (resp.errCode) {
              case WXSuccess:
              {//分享成功
                  
                  [Utilities showToast:@"  分享成功  "];
              }
                  break;
              case WXErrCodeUserCancel:
                  break;
              default:
              {//分享失败
                  
              }
                  break;
          }

    }else if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp* authResp = (SendAuthResp*)resp;
        /* Prevent Cross Site Request Forgery */
        if ([authResp.state isEqualToString:@"huayuancrm"]) {
            if (authResp.code.length > 0) {
                
                [Utilities setToNSUserDefaults:@"huayuancrmOauth" value:authResp.code];
                NSLog(@"%@",authResp.code);
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"huayuancrmOauth" object:nil];
                });
            }else{
                [Utilities showToast:@"微信登录失败"];
            }
        }else{
            [Utilities showToast:@"微信登录失败"];
        }
    }
}

#pragma mark push------SDK启动成功返回cid
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
    //个推SDK已注册，返回clientId
    NSLog(@"\n>>>[GeTuiSdk RegisterClient]:%@\n\n", clientId);

    [TTUserModel sharedObject].clientId = clientId;
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    //doBackground
    TIMBackgroundParam  *param = [[TIMBackgroundParam alloc] init];
    [[TIMManager sharedInstance] doBackground:param succ:^() {
        NSLog(@"doBackgroud Succ");
    } fail:^(int code, NSString * err) {
        NSLog(@"Fail: %d->%@", code, err);
    }];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [[TIMManager sharedInstance] doForeground:^() {
        NSLog(@"doForegroud Succ");
    } fail:^(int code, NSString * err) {
        NSLog(@"Fail: %d->%@", code, err);
    }];
}

#pragma mark  push------APP已经接收到“远程”通知(推送) - 透传推送消息
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
    // 处理APNs代码，通过userInfo可以取到推送的信息（包括内容，角标，自定义参数等）。如果需要弹窗等其他操作，则需要自行编码。
    
    if ([userInfo isKindOfClass:[NSDictionary class]] && [userInfo[@"aps"] isKindOfClass:[NSDictionary class]]) {
        [TT_Alert alert:userInfo[@"aps"][@"alert"]];
    }

    //静默推送收到消息后也需要将APNs信息传给个推统计
    [GeTuiSdk handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

#pragma mark push------远程通知注册成功委托
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    [GeTuiSdk registerDeviceTokenData:deviceToken];
    
    [TTUserModel sharedObject].deviceToken = deviceToken;
}


#pragma mark  push------iOS10以后  为处理 APNs 通知点击事件，统计有效用户点击数
//#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0

//  iOS 10: App在前台获取到通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler  API_AVAILABLE(ios(10.0)){
    
    NSLog(@"willPresentNotification：%@", notification.request.content.userInfo);
    
    NSDictionary *pushDic = notification.request.content.userInfo;
    
    //先展示，展示后用户确定了再跳
    if ([pushDic isKindOfClass:[NSDictionary class]] && [pushDic.allKeys containsObject:@"payload"]) {
                
        NSString *payload = [pushDic valueForKey:@"payload"];
    }
    
    // 根据APP需要，判断是否要提示用户Badge、Sound、Alert
    if (@available(iOS 10.0, *)) {
        completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
    } else {
        // Fallback on earlier versions
    }
}

#pragma mark  push------iOS 10: 点击通知进入App时触发，在该方法内统计有效用户点击数
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler  API_AVAILABLE(ios(10.0)){
    
    NSLog(@"didReceiveNotification：%@", response.notification.request.content.userInfo);

    NSDictionary *pushDic = response.notification.request.content.userInfo;
    if ([pushDic isKindOfClass:[NSDictionary class]] && [pushDic.allKeys containsObject:@"payload"]) {
                
        NSString *payload = [pushDic valueForKey:@"payload"];
        [[TT_JumpManager sharedManager] jumpWithPayload:payload];
    }
    
    [GeTuiSdk handleRemoteNotification:response.notification.request.content.userInfo];
    completionHandler();
}

-(void)setbadge:(NSInteger)badge {
    [GeTuiSdk setBadge:badge]; //同步本地角标值到服务器
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:badge]; //APP 显示角标需开
}


@end
